package com.tencent.cloud.iov.kernel.service.interceptor;

import android.text.TextUtils;

import com.tencent.cloud.iov.kernel.IovKernel;
import com.tencent.cloud.iov.kernel.constant.CookieConst;
import com.tencent.cloud.iov.kernel.constant.HttpHeaderConst;
import com.tencent.cloud.iov.kernel.util.CookieUtils;
import com.tencent.cloud.iov.util.storage.TXSharedPreferencesUtils;

import java.io.IOException;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Cookie 拦截器：处理请求头中cookie，处理更新响应cookie
 *
 * @author vinsonhuang
 * @date 2018/5/30
 */
public class CookieInterceptor implements Interceptor {

    private static final String TAG = CookieInterceptor.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {

        // 处理请求cookie
        Request request = handleRequestCookie(chain);

        // 从响应中取出cookie, 校验更新本地存储的cookie
        Response response = handleResponseCookie(chain.proceed(request));

        return response;
    }

    /**
     * 处理请求cookie，
     *
     * @param chain
     * @return
     */
    private Request handleRequestCookie(Chain chain) {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();

        // header添加companyID
        builder.header(HttpHeaderConst.COMPANY_ID_KEY, String.valueOf(IovKernel.getCompanyId()));

        if (TextUtils.isEmpty(request.header(HttpHeaderConst.ADD_COOKIE_KEY))) {
            return builder.build();
        }
        builder.removeHeader(HttpHeaderConst.ADD_COOKIE_KEY);

        String host = request.url().host();
        String userId = TXSharedPreferencesUtils.getValue(CookieUtils.getUserIdKey(host));
        String userSig = TXSharedPreferencesUtils.getValue(CookieUtils.getUserSigKey(host));
        String accountSessionId = TXSharedPreferencesUtils.getValue(
                CookieUtils.getAccountSessionIdKey(host));
        String accessSessionId = TXSharedPreferencesUtils.getValue(
                CookieUtils.getAccessSessionIdKey(host));
        String gateWaySessionId = TXSharedPreferencesUtils.getValue(
                CookieUtils.getGateWaySessionIdKey(host));

        StringBuilder cookieValues = new StringBuilder();
        cookieValues.append(userId).append(";").append(userSig).append(";")
                .append(accountSessionId).append(";").append(accessSessionId)
                .append(gateWaySessionId).append(";");
        builder.header(HttpHeaderConst.COOKIE_KEY, cookieValues.toString());
        return builder.build();
    }

    /**
     * 处理响应cookie
     *
     * @param response
     * @return
     */
    private Response handleResponseCookie(Response response) {
        List<String> cookies = response.headers(HttpHeaderConst.SET_COOKIE_KEY);
        if (null == cookies || cookies.isEmpty()) {
            return response;
        }

        String host = response.request().url().host();
        for (String cookie : cookies) {
            // preferences中cookie对应的key为: host@Cookie
            String cookieKey;
            String preferencesCookieKey;
            if (cookie.contains(CookieConst.USER_ID)) {
                cookieKey = CookieConst.USER_ID;
                preferencesCookieKey = CookieUtils.getUserIdKey(host);
            } else if (cookie.contains(CookieConst.USER_SIG)) {
                cookieKey = CookieConst.USER_SIG;
                preferencesCookieKey = CookieUtils.getUserSigKey(host);
            } else if (cookie.contains(CookieConst.IOV_ACCOUNT_SESSION_ID)) {
                cookieKey = CookieConst.IOV_ACCOUNT_SESSION_ID;
                preferencesCookieKey = CookieUtils.getAccountSessionIdKey(host);
            } else if (cookie.contains(CookieConst.IOV_ACCESS_SESSION_ID)) {
                cookieKey = CookieConst.IOV_ACCESS_SESSION_ID;
                preferencesCookieKey = CookieUtils.getAccessSessionIdKey(host);
            } else if (cookie.contains(CookieConst.IAM_GATEWAY_SESSIONID)) {
                cookieKey = CookieConst.IAM_GATEWAY_SESSIONID;
                preferencesCookieKey = CookieUtils.getGateWaySessionIdKey(host);
            } else {
                continue;
            }

            if (!isCookieValid(cookie, cookieKey)) {
                continue;
            }

            String oldCookieValue = TXSharedPreferencesUtils.getValue(preferencesCookieKey);
            if (!cookie.equals(oldCookieValue)) {
                TXSharedPreferencesUtils.setValue(preferencesCookieKey, cookie);
            }
        }

        return response;
    }

    /**
     * 判断cookie值是否有效（不为空）
     * <p>
     * 1、获取key在cookie中的开始下标
     * 2、以key的开始下标，截取cookie字符串（keyString），保证key在截取后的字符串中处于开始位置
     * 3、获取keyString中第一个"="下标beginIndex
     * 4、获取keyString中第一个";"下标endIndex
     * 5、计算endIndex-beginIndex的值，若小于等于1，则值为空（无效），若大于1，则有值（有效）
     *
     * @param cookie
     * @param key
     * @return
     */
    private boolean isCookieValid(String cookie, String key) {
        int keyBeginIndex = cookie.indexOf(key);
        if (keyBeginIndex < 0) {
            return false;
        }
        String keyString = cookie.substring(keyBeginIndex);
        int valueBeginIndex = keyString.indexOf("=");
        int valueEndIndex = keyString.indexOf(";");
        if (valueEndIndex - valueBeginIndex <= 1) {
            return false;
        }
        return true;
    }
}
